<?php

namespace api\channel\meituan\alliance;

use app\model\BaseSupplier;
use app\model\CouponOrder;
use Carbon\Carbon;
use MeituanUnion\Client;
use MeituanUnion\BusinessLine;
use GuzzleHttp\Exception\GuzzleException;
use MeituanUnion\request\OrderListRequest;
use MeituanUnion\request\OrderRequest;
use think\Exception;

/**
 * Class Seckill
 * @package api\channel\meituan\alliance
 * 美团分销联盟文档：
 * https://pub.meituan.com/#/api-doc
 * SDK https://github.com/yzchan/meituan-union-php
 */
class Takeout extends MeituanAllianceBase
{

    protected $client;

    public function __construct()
    {
        parent::__construct(PRODUCT_MEITUAN_TAKEOUT_SERV, BaseSupplier::CODE_MEITUAN_WAIMAI);

        $secret = $this->supplierInfo->api_config['secret'];
        $apikey = $this->supplierInfo->api_config['apikey'];

        $this->client = new Client($apikey, $secret);
    }

    public function orders($params)
    {

        $page = $params['page'] ?? 1;

        // 订单列表查询
        $request = new OrderListRequest();
        $request->setBusinessLine(BusinessLine::WAIMAI);


//        $request->setDate(Carbon::now()->format('Y-m-d'));

        $request->setStartTime(Carbon::now()->subDays()->timestamp);
        $request->setEndTime(Carbon::now()->timestamp);

        $request->setPage($page);

        $request->setLimit(100);

        $request->setQueryByModtime(); //订单更新状态

        $response = $this->client->execute($request);

        if (!isProd()){
            var_dump($response);
        }
        \app\model\CurlRequestLog::addRecord([
            'url' => 'meituanwaimai',
            'request' => 'meituanwaimai' ,
            'response' => is_array($response) ? json_encode($response, JSON_UNESCAPED_UNICODE) : '',
        ]);

        $res['data'] = $response["dataList"] ?? [];

        return $res;

    }

    /**
     * 获取单条记录
     */
//    public function getOneOrder($couponOrder)
//    {
//        /**
//         * @var CouponOrder $couponOrder
//         */
//        $request = new OrderRequest();
//        $request->setOrderId($couponOrder->supplier_order_sn);
//        $request->setFull(false);
//
//
//        if (empty($couponOrder->couponOrderSid)) return [];
//        if (empty($couponOrder->couponOrderSid->act_id)) return [];
//
//        $request->setActId($couponOrder->couponOrderSid->act_id);
//
//        $request->setBusinessLine(BusinessLine::WAIMAI);
//
//        $response = $this->client->execute($request);
//
//        $res['data'] = $response["data"] ?? [];
//
//        return $res;
//    }
}